import json
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
from django.contrib.auth.models import AnonymousUser
from .models import Game


class GameConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.game_id = self.scope['url_route']['kwargs']['game_id']
        self.game_group_name = f'game_{self.game_id}'
        
        # 检查用户是否参与此游戏
        if await self.check_user_permission():
            # 加入游戏组
            await self.channel_layer.group_add(
                self.game_group_name,
                self.channel_name
            )
            
            await self.accept()
        else:
            await self.close()
    
    async def disconnect(self, close_code):
        # 离开游戏组
        await self.channel_layer.group_discard(
            self.game_group_name,
            self.channel_name
        )
    
    async def receive(self, text_data):
        try:
            text_data_json = json.loads(text_data)
            message_type = text_data_json.get('type')
            
            if message_type == 'game_status':
                # 发送游戏状态
                game_status = await self.get_game_status()
                await self.send(text_data=json.dumps({
                    'type': 'game_status',
                    'data': game_status
                }))
            
        except json.JSONDecodeError:
            await self.send(text_data=json.dumps({
                'type': 'error',
                'message': 'Invalid JSON'
            }))
    
    async def game_update(self, event):
        # 发送游戏更新到WebSocket
        await self.send(text_data=json.dumps({
            'type': 'game_update',
            'data': event['data']
        }))
    
    @database_sync_to_async
    def check_user_permission(self):
        """检查用户是否有权限访问此游戏"""
        user = self.scope['user']
        if isinstance(user, AnonymousUser):
            return False
        
        try:
            game = Game.objects.get(id=self.game_id)
            return user in [game.player1, game.player2]
        except Game.DoesNotExist:
            return False
    
    @database_sync_to_async
    def get_game_status(self):
        """获取游戏状态"""
        try:
            game = Game.objects.get(id=self.game_id)
            from .game_logic import GameLogic
            return GameLogic.get_game_status(game)
        except Game.DoesNotExist:
            return None
